<?php

namespace App\Admin\Forms;

use App\Models\ProjectAgreement;
use App\Models\ProjectExportRecordsDetail;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BatchAuditPayStatusForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public $elementId = 'audit-pay';

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        // 获取选中的导出记录
        $projectAgreementList = ProjectAgreement::whereIn('id', explode(',', $input['id']))->get();
        dd($projectAgreementList);

        // 当前审核记录
        $log = [
            [
                'audit_global_status' => 2,
                'audit_user' => Admin::user()->name,
                'audit_time' => date('Y-m-d H:i:s'),
                'pay_status' => $input['pay_status'],
                'audit_remark' => $input['audit_remark'] ?? '',
                // 'audit_fee' => $input['pay_status'],
            ],
        ];

        try {

            foreach ($projectAgreementList as $key => $val) {
                $lastLog = empty(json_decode($val['audit_log'], true)) ? [] : json_decode($val['audit_log'], true);

                \App\Models\ProjectAgreement::where('id', $val['project_agreement_id'])
                    ->update([
                        // 'audit_fee' => $input['pay_status'], // 劳务审核
                        // 'status' => $input['pay_status'],
                        'audit_remark' => ($input['pay_status'] == 1 ? '' : $input['audit_remark']),
                        'audit_log' => \json_encode(array_merge($lastLog, $log), 256),
                        'pay_status' => $input['pay_status'],
                    ]);
            }

            return $this
                ->response()
                ->success('操作成功')
                ->refresh();
        } catch (\Exception $e) {
            Log::info('----------catch----------', ['exception' => json_encode($e)]);
            return $this
                ->response()
                ->error('操作失败')
                ->refresh();
        }
    }


    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('pay_status', '审核状态')->options(['1' => '允许支付', '-1' => '审核驳回'])->when(
            '-1',
            function (Form $form) {
                $form->textarea('audit_remark', '审核意见');
            }
        )->required();
        // 设置隐藏表单，传递用户id
        $this->hidden('id')->attribute('id', 'reset-password-id');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function
    default()
    {

        return [];
    }
}
